from typing import *


class NeighborSum:

    def __init__(self, grid: List[List[int]]):
        self.g = grid
        self.m, self.n = len(grid), len(grid[0])
        d = {}
        for i in range(self.m):
            for j in range(self.n):
                d[grid[i][j]] = (i, j)
        self.h = d
        self.a = ((1, 0), (-1, 0), (0, 1), (0, -1))
        self.b = ((1, 1), (-1, -1), (1, -1), (-1, 1))

    def adjacentSum(self, value: int) -> int:
        g = self.g
        i, j = self.h[value]
        ans = 0
        for x, y in self.a:
            p, q = i + x, j + y
            if p >= self.m or q >= self.n or p < 0 or q < 0:
                continue
            ans += g[p][q]
        return ans

    def diagonalSum(self, value: int) -> int:
        g = self.g
        i, j = self.h[value]
        ans = 0
        for x, y in self.b:
            p, q = i + x, j + y
            if p >= self.m or q >= self.n or p < 0 or q < 0:
                continue
            ans += g[p][q]
        return ans


# Your NeighborSum object will be instantiated and called as such:
# obj = NeighborSum(grid)
# param_1 = obj.adjacentSum(value)
# param_2 = obj.diagonalSum(value)
